import 'dart:convert';

import 'package:dmz/request/config.dart';
import 'package:dmz/routers/routers.dart';
import 'package:dmz/user/user_model.dart';
import 'package:dmz/utils/preference_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

class EMIBUserManger {
  factory EMIBUserManger() => _instance;

  static final EMIBUserManger _instance = EMIBUserManger._internal();

  EMIBUserManger._internal() {
    init();
  }

  String token = '';
  String? snCode;
  UserEntity? user;
  Locale? locale;

  init() {
    var data = PreferenceUtils().getString('user');
    if (data.isNotEmpty) user = UserEntity.fromJson(jsonDecode(data));
  }

  ///多语言初始化
  initLanguage() {
    // ignore: deprecated_member_use
    Locale currentLocale = WidgetsBinding.instance.window.locale;
    var code = Get.locale?.languageCode;
    var data = PreferenceUtils().getString('language',
        '${currentLocale.languageCode},${currentLocale.countryCode}');

    List<String> datas = data.split(',');
    if (code != datas.first) {
      locale = Locale(datas.first, datas.last);
      Get.updateLocale(Locale(datas.first, datas.last));
    }
  }

  ///保存token
  saveToken(String? tokened) {
    token = tokened!;
    PreferenceUtils().putString('token', tokened);
  }

  saveUser(UserEntity data) {
    user = data;
    PreferenceUtils().putString('user', jsonEncode(data.toJson()));
  }

  ///本地存储更新
  upadtaSave() {
    PreferenceUtils().putString('user', jsonEncode(user?.toJson()));
  }

  ///获取token
  getToken() {
    token = PreferenceUtils().getString('token');
    debugPrint('获取token -- $token');
  }

  ///打开浏览器 查看协议、隐私
  launchURL(int type) async {
    var url = Uri.parse(type == 0
        ? '${RequestConfig.baseUrl}/html/userAgreement.html'
        : '${RequestConfig.baseUrl}/html/privacyAgreement.html'); // 你想要打开的URL

    if (!await launchUrl(url)) {
      throw Exception('Could not launch $url');
    }
  }

  ///退出登录
  logout({bool cleanData = true}) {
    if (cleanData) {
      Get.find<SharedPreferences>().remove('token');
      user = null;
      PreferenceUtils().putString('user', '');
    }
    Get.offAllNamed(RouteGet.loginFirst);
  }
}
